package com.ibiaoke.boss.common.intercepter;

import com.ibiaoke.boss.entity.SysUser;
import com.ibiaoke.common.consts.CommonConsts;
import com.ibiaoke.common.response.Res;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by huhaichao on 2017/6/6.
 */
public class LoginInterceptor implements HandlerInterceptor {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    String[] passUrls = {
            "login.do"
            ,"sshToken.do"
            ,"RegisterUser.do"
            ,"listGoodsClass.do"
            ,"FindPtGood.do"
            ,"SavePtGoods.do"
            ,"updatePtGood.do"
            ,"getPtOrderDeail.do"
            ,"getPtOrderByExcel.do"
            ,"addStock.do"
            ,"findGoodStockList.do"
            ,"addAdjust.do"
            ,"findAdjustList.do"
            ,"addReportLoss.do"
            ,"findReportLossList.do"
            ,"addChenk.do"
            ,"getGoodCount.do"
            ,"findCheckList.do"
            ,"addReserveGoods.do"
            ,"findReserveGoodsList.do"
            ,"addXcxReduceGoods.do"
            ,"xcxGoodsList.do"
            ,"listXcxGoodsClass.do"
            ,"market.do"
            ,"batchSaveXcxShopPrice.do"
    };

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        if("OPTIONS".equalsIgnoreCase(request.getMethod())){
            return true;
        }
        response.setHeader("Access-Control-Allow-Origin", "*");
        //不拦截
        for (String passUrl : passUrls) {
            if (request.getRequestURI().indexOf(passUrl) >= 0) {
                return true;
            }
        }

        SysUser user = (SysUser) request.getSession().getAttribute(CommonConsts.LOGIN_SESSION_NAME);
           if (user == null) {
            response.getWriter().write(Res.createErrorRes("not login").toJson());
            return false;
        }else {
            logger.info("用户:{}", user.getUserName());
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
